<template>
  <div>
    <el-form ref="form" :model="form" label-width="70px" class="form-content" style="padding-right: 15px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="封　　面">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{ Authorization: token }"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="博客标题">
            <el-input v-model="form.blogTitle" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分　　类">
            <el-select
              v-model="form.blogType"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标　签">
            <el-select
              v-model="bindTagList"
              style="width: 100%"
              multiple
              filterable
              remote
              :remote-method="getTag"
              allow-create
              default-first-option
              placeholder="请选择标签"
            >
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id + '::' + item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="简　　介">
            <el-input
              v-model="form.blogRemark"
              type="textarea"
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章来源">
            <el-input v-model="form.blogSource"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="内　　容">
            <tinymce ref="tinymce" v-model="form.blogContent" :height="300" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="toUpdate">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { toUpdate, getUpdate } from "@/api/blog";
import { list } from "@/api/type";
import { searchByName, getByBlogId } from "@/api/tag";
import Tinymce from "@/components/Tinymce";
import { mapGetters } from "vuex";

export default {
  components: {
    Tinymce,
  },
  props: {
    activeId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      form: {},
      // 分类列表
      typeList: [],
      // 绑定的标签列表
      bindTagList: [],
      // 标签列表
      tagList: [],
      // 封面地址
      imageUrl: "",
      // 文件上传地址
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
    };
  },
  computed: {
    ...mapGetters(["token"]),
  },
  watch: {
    // 当id改变时，加载数据
    activeId: {
      // 饥饿监听  第一次赋值也需要调用该方法
      immediate: true,
      handler: function (newVal, oldVal) {
        this.getById();
        this.getOldTag();
      },
    },
  },
  created() {
    this.getTypeList();
  },
  methods: {
    // 查询回显数据
    getById() {
      getUpdate(this.activeId).then((res) => {
        this.form = res.data;
        this.imageUrl = res.data.blogImage;
        if (this.form.blogContent) {
          this.$refs.tinymce.setContent(this.form.blogContent);
        } else {
          this.$refs.tinymce.setContent("");
        }
      });
    },
    // 远程搜索标签
    getTag(data) {
      // 如果标签存在，调用方法
      if (data) {
        searchByName(data).then((res) => {
          this.tagList = res.data;
        });
      }
    },
    // 加载分类列表
    getTypeList() {
      list().then((res) => {
        this.typeList = res.data;
      });
    },
    // 查询回显标签
    getOldTag() {
      getByBlogId(this.activeId).then((res) => {
        this.tagList = res.data;
        const temp = [];
        res.data.forEach((e) => {
          // 用id::name构造元素
          temp.push(e.id + "::" + e.name);
        });
        this.bindTagList = temp;
      });
    },
    // 更新
    toUpdate() {
      this.form.blogImage = this.imageUrl;
      const tagArr = [];
      this.bindTagList.forEach((e) => {
        // 根据 :: 截取
        const temp = e.split("::");
        if (temp.length === 2) {
          // 远程搜索的标签
          tagArr.push({ id: temp[0], name: temp[1] });
        } else if (temp.length === 1) {
          // 自定义标签
          tagArr.push({ name: temp[0] });
        }
      });
      this.form.tagList = tagArr;
      toUpdate(this.form).then((res) => {
        this.$message.success(res.msg);
        this.$emit("after");
        this.$emit("closeDialog");
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit("closeDialog");
    },
    //  限制用户上传的图片格式和大小
    beforeAvatarUpload(file) {
      const isPng = file.type === "image/png";
      const isJPG = file.type === "image/jpeg";
      const isBpm = file.type === "image/bmp";
      const isGif = file.type === "image/gif";

      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!(isJPG || isPng || isBpm || isGif)) {
        this.$message.error("上传头像图片只能是 JPG/Png/Bpm/Gif 格式!");
      }

      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      if (isPng) {
        return isPng && isLt10M;
      } else if (isJPG) {
        return isJPG && isLt10M;
      } else if (isBpm) {
        return isBpm && isLt10M;
      } else if (isGif) {
        return isGif && isLt10M;
      }
    },
    // 回显图片地址
    handleAvatarSuccess(res) {
      this.imageUrl = res.data.path;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 160px;
  display: block;
}
.form-content {
  height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
}
</style>